import { useReducer, useState } from "react";

function UseReducerDemo() {



    const [list, dispatch] = useReducer((state, action) => {
        const { data, type } = action
        switch (type) {
            case "ADD":
                return [...state, data];
            case "DELETE":
                return state.filter((item, i) => i !== data);
            case "UPDATE":
                return state.map((item, i) => i === data ? item + '修改' : item);
            default:
                return state
        }

    }, ["a", "b", "c"])

    // const [list,setList]=useState(["1",2,3]);
    // const add=()=>{
    //     setList([...list,list.length+1]);
    // }
    // const del=(index:number)=>{
    //     setList(list.filter((item,i)=>i!==index));
    // }
    // const edit=(index:number)=>{
    //     setList(list.map((item,i)=>i===index?item+'修改':item));
    // }

    return (
        <div>
            UseReducerDemo

            <div>

                <ul>
                    {list.map((item, index) => {
                        return <li key={index}>{item}
                            <button onClick={() => dispatch({ type: "DELETE", data: index })}>删除</button>
                            <button onClick={() => dispatch({ type: "UPDATE", data: index })}>修改</button>
                        </li>
                    })}
                </ul>

                <button onClick={() => dispatch({ type: "ADD", data: 'd' })}>添加</button>



                {/*  
              <ul>
                  {list.map((item,index)=>{
                      return <li key={index}>{item}
                      <button onClick={()=>del(index)}>删除</button>
                      <button onClick={()=>edit(index)}>修改</button>
                      </li>
                  })}
              </ul>

              <button onClick={add}>添加</button> */}




            </div>
        </div>
    )

}
export default UseReducerDemo;